import tkinter as tk
from tkinter import ttk
import sqlite3
from datetime import datetime
# 新增matplotlib后端配置
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

class EnvironmentPage(ttk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller
        
        # 实时数据框架
        self.realtime_frame = ttk.LabelFrame(self, text="实时监测")
        self.realtime_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
        
        # 温度显示
        self.temp_label = ttk.Label(self.realtime_frame, text="温度: -- ℃")
        self.temp_label.grid(row=0, column=0, padx=10, pady=5, sticky='w')
        

        
        self.humi_label = ttk.Label(self.realtime_frame, text="湿度: -- %")
        self.humi_label.grid(row=1, column=0, padx=10, pady=5, sticky='w')
        
        # 湿度显示
        self.humi_label = ttk.Label(self.realtime_frame, text="湿度: -- %")
        self.humi_label.grid(row=1, column=0, padx=5, pady=5)
        
        # 烟雾报警
        self.smoke_indicator = ttk.Label(self.realtime_frame, text="烟雾: 正常", 
                                      background="#90EE90")
        self.smoke_indicator.grid(row=2, column=0, padx=5, pady=5)
        
        # 图表按钮
        self.chart_btn = ttk.Button(self.realtime_frame, text="查看历史曲线",
                                  command=self.show_history_chart)
        self.chart_btn.grid(row=3, column=0, pady=10)
        
        # 图表框架
        self.chart_frame = ttk.Frame(self)
        self.chart_frame.grid(row=0, column=1, sticky="nsew", padx=10)
        
        # 配置网格权重
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=3)
        self.grid_rowconfigure(0, weight=1)

    def update_data(self):
        try:
            conn = sqlite3.connect('sensor_data.db')
            c = conn.cursor()
            c.execute("SELECT temperature, humidity, smoke FROM sensor_data ORDER BY timestamp DESC LIMIT 1")
            data = c.fetchone()
            
            if data:
                self.temp_label.config(text=f"温度: {data[0]} ℃")
                self.humi_label.config(text=f"湿度: {data[1]} %")
                self.smoke_indicator.config(
                    text="烟雾: 报警" if data[2] else "烟雾: 正常",
                    background="#FF9999" if data[2] else "#90EE90"
                )
            conn.close()
        except Exception:
            pass

    def show_history_chart(self):
        # 清除旧组件并创建新画布
        for widget in self.chart_frame.winfo_children():
            widget.destroy()
        canvas = tk.Canvas(self.chart_frame)
        
        # 调试信息
        print(f'当前chart_frame子组件数量: {len(self.chart_frame.winfo_children())}')
        print(f"新画布路径: {str(canvas)}")
        print(f'父容器路径: {str(self.chart_frame)}')
        
        # 从数据库获取最近7天数据
        conn = sqlite3.connect('sensor_data.db')
        c = conn.cursor()
        c.execute("SELECT timestamp, temperature, humidity FROM sensor_data WHERE timestamp > datetime('now','-7 days') ORDER BY timestamp ASC")
        data = c.fetchall()
        conn.close()
        
        if data:
            timestamps = [row[0] for row in data]
            temps = [row[1] for row in data]
            humis = [row[2] for row in data]
            
            # 计算坐标参数
            max_temp = max(temps)
            min_temp = min(temps)
            max_humi = max(humis)
            
            # 计算Y轴比例尺
            if max_temp != min_temp:
                y_scale = (350-50)/(max_temp - min_temp)
            else:
                y_scale = 1  # 温度数据相同时使用默认比例
            
            # 绘制坐标轴及标签
            canvas.create_line(50, 50, 50, 350, width=2)  # Y轴
            canvas.create_line(50, 350, 550, 350, width=2)  # X轴
            
            # 计算X轴天数
            first_date = datetime.strptime(timestamps[0], '%Y-%m-%d %H:%M:%S')
            day_labels = [(datetime.strptime(ts, '%Y-%m-%d %H:%M:%S') - first_date).days for ts in timestamps]
            
            # 有效性验证
            if not day_labels or max(day_labels) == 0:
                day_labels = [0, 1]  # 默认两天跨度
            
            # 安全计算时间间隔
            try:
                x_interval = (550-50)/max(day_labels)
            except ZeroDivisionError:
                x_interval = 500  # 默认500像素跨度
            
            # 绘制X轴刻度
            for day in set(day_labels):
                x_pos = 50 + day * x_interval
                canvas.create_line(x_pos, 350, x_pos, 345, width=1)
                canvas.create_text(x_pos, 360, text=f"第{day}天", font=('Microsoft YaHei', 8))
            
            # 绘制Y轴刻度
            if max_temp > min_temp:
                temp_interval = (max_temp - min_temp)/5
                for i in range(6):
                    value = min_temp + i*temp_interval
                    y_pos = 350 - (value - min_temp)*y_scale
            else:
                canvas.create_text(100, 200, text="温度数据无效", fill='red')
                canvas.create_line(45, y_pos, 50, y_pos, width=1)
                canvas.create_text(40, y_pos, text=f"{value:.1f}℃", anchor='e', font=('Microsoft YaHei', 8))
            
            # 安全绘制图表
            try:
                # 绘制温度折线
                self._draw_matplotlib_chart(temps, humis, timestamps)
                # 绘制湿度折线
                self._draw_polyline(canvas, humis, 50, 350, 550, 350, max_humi, 0, '#0000FF')
            except Exception as e:
                print(f"绘图错误: {e}")
                ttk.Label(self.chart_frame, text="图表渲染失败，请检查数据", foreground="red").pack()
            
            # 添加图例
            canvas.create_text(100, 380, text="温度", fill='#FF0000', font=('Microsoft YaHei', 10))
            canvas.create_text(200, 380, text="湿度", fill='#0000FF', font=('Microsoft YaHei', 10))
            
            canvas.pack(fill='both', expand=True)
        else:
            print("数据库无有效数据")

    # 更新图表生成方式
    def _draw_matplotlib_chart(self, temps, humis, timestamps):
        from matplotlib.dates import DateFormatter, DayLocator
        
        # 转换时间格式
        dates = [datetime.strptime(ts, '%Y-%m-%d %H:%M:%S') for ts in timestamps]
        
        fig = Figure(figsize=(6, 4))
        ax = fig.add_subplot(111)
        ax.plot(dates, temps, 'r-', label='温度')
        
        # 设置日期格式化
        date_format = DateFormatter('%m/%d')
        ax.xaxis.set_major_formatter(date_format)
        ax.xaxis.set_major_locator(DayLocator(interval=1))
        fig.autofmt_xdate(rotation=45)
        ax.plot(dates, humis, 'b-', label='湿度')
        ax.set_xlabel('时间')
        ax.set_ylabel('数值')
        ax.legend()
        canvas = FigureCanvasTkAgg(fig, master=self.chart_frame)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        x_step = (x_end - x_start) / (max(days) if days else 1)
        y_scale = (y_base_end - 50) / (max_val - min_val) if max_val > min_val else 1
        
        points = []
        for i, value in enumerate(data):
            x = x_start + i * x_step
            y = y_base - (value - min_val) * y_scale
            points.extend([x, y])
        
        canvas.create_line(points, fill=color, width=2)
        
        # 添加数据点标记
        for x, y in zip(points[::2], points[1::2]):
            canvas.create_oval(x-3, y-3, x+3, y+3, fill=color)